import React, { useEffect, useState } from 'react';
import { $getImg } from '../../api/getImgapi';
import { Input,Button} from 'antd';
const { TextArea } = Input;
import {HeartOutlined,MessageOutlined} from '@ant-design/icons';
import SubComments from '../subcomment/subcomment';
import {$Newcomment} from "../../api/commentapi";
import MyNotification from "../MyNotification/MyNotification";

const Comment = ({comment,avater}) => {
  //空值评论框的出现
  const [showComments, setShowComments] = useState(false);
  //获取输入框评论内容的实时更新
  const [comment1, setComment1] = useState('');
  //通知框状态
  const [notiMsg, setNotiMsg] = useState({type: "", description: ""});
  //回复评论
  const reply=async()=>{
    setShowComments(!showComments);//显示按钮的状态是否评论已近点开
  }
  //获取评论个人头像
  const [data,setData]=useState(null);
  useEffect(()=>{
    const response=$getImg({ studentId: comment.studentId.toString() });
    response.then((result) => {
      if(result.code===1){
        const { data } = result;
        setData(data);
      }
      });
       // 使用Date对象解析原始日期时间字符串
const originalDateTime = new Date(comment.createdAt);
// 获取所需的日期时间格式，例如 "YYYY-MM-DDTHH:MM"
setFormattedDateTime( originalDateTime.toISOString().slice(0, 10))
setSubComment(comment.sonComments);
  },[])
  //转换时间
const [formattedDateTime,setFormattedDateTime]=useState('');

// 用于切换是否显示所有评论
const [showAllComments, setShowAllComments] = useState(false);
// 点击查看剩余评论按钮时的处理函数
  const handleShowAllComments = () => {
    setShowAllComments(true); // 显示所有评论
  };
    // //点击头像函数
    // const handleAvatarClick = (studentId) => {
    //   navigate(`/othermine/${studentId}`);
    // };
//子评论数据
const [subComments,setSubComment]= useState([]);
 // 只显示前两个子评论
 const visibleComments = subComments && subComments.length > 2 && !showAllComments ? subComments.slice(0, 2) : subComments;
 //输入框的回调函数，及时更新输入框的内容
  const handleCommentChange1 = (event) => {
    setComment1(event.target.value);
  };
  //生成新的评论的回复
  const handlePublish = async() => {
    const response =await $Newcomment({commentId:comment.commentId,content:comment1});
    if (response.code) {
      setNotiMsg({ type: "success", description: response.message});
    } else {
      setNotiMsg({ type: "error", description: response.message })
    }
    setComment1('');
  };
  return(
  <div>
    <div className="AuthorInfo" style={{marginBottom:"20px"}}>
      <div>
      <img src={`data:image/jpeg;base64,${data}`}  alt="获取图片失败" style={{ width:'30px',height:'30px', marginRight:'5px'}} />
      <span>{comment.nickname}</span>
      </div>
            </div>
    <p>{comment.content}</p>
    <div style={{marginBottom:'20px',display:'flex',justifyContent:"space-between",alignItems:'center'}}>
    <span className='right'>{formattedDateTime}</span>
    <span>
    <Button icon={<HeartOutlined/>} style={{border: 'none'}}>{comment.likeNum}</Button>
    <Button icon={<MessageOutlined/>} style={{border: 'none'}} onClick={reply}>{showComments?'收起':'回复'}</Button>
    </span>
    </div>
    <div>
      {showComments && <div>
        <div style={{
          display: "flex",
          alignItems: "center",
          marginTop: "20px",
          marginBottom: "20px"
        }}>
          <img src={`data:image/jpeg;base64,${avater}`} alt="获取图片失败"
               style={{width: '50px', height: '50px'}}/>
          <textarea
              value={comment1}
              onChange={handleCommentChange1}
              placeholder="欢迎参加讨论"
              style={{width: '80vw'}}
              autoSize={{
                minRows: 2,
                maxRows: 6,
              }}
          />
          <Button type="primary" onClick={
            handlePublish}
                  style={{backgroundColor: 'rgb(178, 234, 230)', width: '60px', height: "40px"}}>
            发布
          </Button>

        </div>
      </div>}
      {visibleComments && visibleComments.map((subComment, index) => (
          <SubComments key={index} SubComment={subComment}/>
      ))}
      {/* 如果子评论数量超过两个，显示查看剩余评论按钮 */}
      {subComments && subComments.length > 2 && !showAllComments && (
          <Button onClick={handleShowAllComments}>查看剩余评论</Button>
      )}
    </div>
    <MyNotification notiMsg={notiMsg}/>
  </div>
  )

};
export default Comment;